package com.rookieCi.qrcodefile.sync;

import android.text.TextUtils;
import android.util.Base64;

import com.google.gson.Gson;
import com.rookieCi.qrcodefile.BuildConfig;
import com.rookieCi.qrcodefile.mode.NoteMode;
import com.rookieCi.qrcodefile.utils.FileOperateUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AcceptFileContact {
    private boolean isInit;//第一张二维码用于初始化
    /**
     * 0-文件，1文本，2-压缩文件，3-压缩文本
     */
    private int sendType;
    private int no;
    private List<String> textList;
    private int codeInt;//-1表示结束
    private OnFileContactInterface contactInterface;

    public AcceptFileContact(OnFileContactInterface contactInterface) {
        this.contactInterface = contactInterface;
    }

    public int getSendType() {
        return sendType;
    }

    public int getCodeInt() {
        return codeInt;
    }

    public int getNo() {
        return no;
    }

    private void init(NoteMode codeMode) {
        if (isInit) return;
        if (codeMode == null) return;
        Integer integer1 = codeMode.no;
        Integer integer2 = codeMode.t;
        if (integer1 == null || integer1 < 0) return;
        if (integer2 == null || integer2 < 0) return;
        no = integer1;
        sendType = integer2;
        isInit = true;
        //codeMode.idx;
        //codeMode.str;
    }

    public boolean acceptText(String text) {
        if (codeInt == -1) return true;
        try {
            NoteMode codeMode = new Gson().fromJson(text, NoteMode.class);
            init(codeMode);
            if (isInit) {
                Integer integer1 = codeMode.no;
                Integer integer2 = codeMode.t;
                if (integer1 == null) return false;
                if (integer2 == null) return false;
                if (no != integer1 || sendType != integer2) return false;
                Integer idx = codeMode.idx;
                String str = codeMode.str;
                if (idx == null || TextUtils.isEmpty(str)) return false;
                if (idx == -1) {//结束
                    codeInt = -1;
                    if (sendType == 1 || sendType == 3) {
                    } else {
                        if (outputStream != null) {
                            outputStream.close();
                            outputStream = null;
                        }
                    }
                    return true;
                } else if (idx == codeInt) {
                    boolean writeFile = true;
                    if (sendType == 1 || sendType == 3) {//文本
                        if (textList == null) textList = new ArrayList<>();
                        textList.add(str);
                    } else {//文件
                        if (!contactInterface.checkFilePermissions()) {
                            return false;
                        }
                        if (codeInt == 0) {//文件名
                            createFile(str);
                        } else {//写入数据
                            writeFile = writeFile(str);
                        }
                    }
                    if (writeFile) codeInt++;
                    return writeFile;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private File file;
    private FileOutputStream outputStream;

    private void createFile(String fileName) {//保存位置
        String folderPath = FileOperateUtil.getInstance().getFolderPath(FileOperateUtil.ROOT);
        file = new File(folderPath, fileName);
        //大部分手机不给权限
        /*String folderPath = FileOperateUtil.getInstance().getSDCard() + File.separator + "Download" + File.separator;
        File folder = new File(folderPath);
        if (!folder.exists()) folder.mkdirs();
        file = new File(folderPath, fileName);*/
    }

    private boolean writeFile(String str) {
        if (outputStream == null) {
            try {
                if (!file.exists()) file.createNewFile();
                outputStream = new FileOutputStream(file);
            } catch (FileNotFoundException e) {
                return false;
            } catch (IOException e) {
                if (BuildConfig.DEBUG) e.printStackTrace();
            }
        }
        try {
            byte[] decode = Base64.decode(str, Base64.DEFAULT);
            outputStream.write(decode);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 类型为文本时使用
     */
    public String getText() {
        StringBuilder builder = new StringBuilder();
        if (textList != null) {
            for (int i = 0; i < textList.size(); i++) {
                builder.append(textList.get(i));
            }
        }
        return builder.toString();
    }

    public String getFilePath() {
        return file == null ? null : file.getAbsolutePath();
    }
}
